package com.yksj.healthtalk.ui.salon;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SearchAdapter;
import com.yksj.healthtalk.adapter.SearchAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 通过名字查找话题
 * 
 * @author jack_tang
 * getIntent().getStringExtra("name")
 * 
 */
public class SalonSeachFromName extends BaseFragmentActivity implements
		OnClickListener, OnRefreshListener<ListView>,
		onClickSalonAttentionListener, OnItemClickListener,
		OnBuyTicketHandlerListener {
	private SearchAdapter<GroupInfoEntity> mSalonAdapter;
	private ArrayList<GroupInfoEntity> entities;
	private ListView mListView;
	private AppData mAppData;
	private ChatUserHelper chatUserHelper;
	private int PAGESIZE = 1;
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(SalonSeachFromName.this,R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestAttentionToSalonResult(
							SalonSeachFromName.this, cacheGroupInfoEntity,mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}

			} else if (action
					.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(SalonSeachFromName.this,
							R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestUnfollowToSalonResult(
							SalonSeachFromName.this, cacheGroupInfoEntity,
							mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			}
		}

	};
	private GroupInfoEntity cacheGroupInfoEntity;
	private GroupInfoEntity mGroupInfoEntity;
	private PullToRefreshListView pullToRefreshListView;
	private String flag = "";
	private String flagPlacing = "-100000";
	private ResponseHandler responseHandler;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.salon_seach_from_name_layout);
		initView();
		responseHandler = new ResponseHandler();
		initData();
	}

	private void initData() {
		mGroupInfoEntity.setFlag(flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, 0, responseHandler);
	}

	class ResponseHandler extends ObjectHttpResponseHandler {

		@Override
		public void onFinish() {
			super.onFinish();
			pullToRefreshListView.onRefreshComplete();
		}

		@Override
		public void onStart() {
			super.onStart();
			pullToRefreshListView.setRefreshing();
		}

		@Override
		public void onSuccess(Object response) {
			super.onSuccess(response);
			if (response == null)
				return;
			if (flagPlacing.equals("-100000")) {
				entities.clear();
			}
			ArrayList<GroupInfoEntity> newEntities = (ArrayList<GroupInfoEntity>) response;
			if (newEntities.size() == 0) {
				ToastUtil.showToastPanl("暂无更多内容...");
				return;
			}
			entities.addAll(newEntities);
			mSalonAdapter.notifyDataSetChanged();
			flag = mSalonAdapter.getPageFlagMark(false, GroupInfoEntity.class);
			flagPlacing = mSalonAdapter.getFlagPlacingMark(false,
					GroupInfoEntity.class);
			if (flagPlacing.equals("-100000")) {
				mListView.setSelection(0);
			}
		}

		@Override
		public Object onParseResponse(String content) {
			if (!content.equals("N")) {
				return SalonHttpUtil.jsonAnalysisSalonEntity(SalonSeachFromName.this, content);
			} else {
				return null;
			}
		}

	}

	private void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setText("创建");
		titleRightBtn2.setOnClickListener(this);
		pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_listview);
		pullToRefreshListView.setOnRefreshListener(this);
		entities = new ArrayList<GroupInfoEntity>();
		titleLeftBtn.setOnClickListener(this);
		mListView = pullToRefreshListView.getRefreshableView();
		mSalonAdapter = new SearchAdapter<GroupInfoEntity>(this, entities);
		mListView.setAdapter(mSalonAdapter);
		mSalonAdapter.setonClickSalonAttentionListener(this);
		mAppData = HTalkApplication.getAppData();
		chatUserHelper = ChatUserHelper.getInstance();
		mListView.setOnItemClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleTextV.setText(getIntent().getStringExtra("name"));
		mGroupInfoEntity = new GroupInfoEntity();
		mGroupInfoEntity.setFlag(flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		mGroupInfoEntity.setPagesize(1);
		mGroupInfoEntity.setType(1);
		mGroupInfoEntity.setCreateCustomerID(SmartFoxClient.getLoginUserId());
		mGroupInfoEntity.setName(getIntent().getStringExtra("name"));
		mGroupInfoEntity.setUpperId("0");
		mGroupInfoEntity.setInfoId("0");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:// 创建
			break;
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_REPEAT_STATE);
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(receiver);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		initData();
	}

	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName,
			int positon) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(this,
				mSalonName);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			SalonHttpUtil.onItemClick(this, this, getSupportFragmentManager(),
					entities.get(position - 1), true);
		} catch (Exception e) {
		}
	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if ("0".equals(state)) {
		} else if ("-1".equals(state)) {
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(getApplicationContext(), ChatActivity.class);
			startActivity(intent1);
		}
	}
}
